/*
 * Copyright (c) 2018, apexes.net. All rights reserved.
 *
 *         http://www.apexes.net
 *
 */
package net.apexes.commons.json.gson;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import net.apexes.commons.lang.Enume;

import java.io.IOException;

/**
 * @param <E>
 * @author <a href="mailto:hedyn@foxmail.com">HeDYn</a>
 */
public class EnumeByIntegerAdapter<E extends Enume<Integer>> extends TypeAdapter<E> {

    private final Class<E> enumeClass;

    public EnumeByIntegerAdapter(Class<E> enumeClass) {
        this.enumeClass = enumeClass;
    }

    @Override
    public void write(JsonWriter out, E value) throws IOException {
        out.value(Enume.toValue(value));
    }

    @Override
    public E read(JsonReader in) throws IOException {
        Integer value;
        if (in.peek() == JsonToken.NULL) {
            value = null;
        } else {
            value = in.nextInt();
        }
        return Enume.fromValue(enumeClass, value);
    }

}
